/*
@hehung
2023-5-22
email: 1398660197@qq.com
wechat: hehung95
reproduced and please indicate the source @hehung
*/

/*******************************************************************************
 * Header include
 ******************************************************************************/
#include "app_common.h"
//#include "oled_imgtab.h"
#include "oled_codetab.h"

#define OLED_DEBUG
#undef OLED_DEBUG

#ifdef OLED_DEBUG
#include <stdio.h>
#define LOG(fmt, ...) 	                printf(fmt, ##__VA_ARGS__)
#else
#define LOG(fmt, ...)
#endif 

/*******************************************************************************
 * Macro Definitions
 ******************************************************************************/
#define OLED_I2C_SLAVE_ADDR_7BIT           (0x3CU)

/*******************************************************************************
 * Static Variables Definitions 
 ******************************************************************************/
//OLED的显存
//存放格式如下.
//[0]0 1 2 3 ... 127
//[1]0 1 2 3 ... 127
//[2]0 1 2 3 ... 127
//[3]0 1 2 3 ... 127
//[4]0 1 2 3 ... 127
//[5]0 1 2 3 ... 127
//[6]0 1 2 3 ... 127
//[7]0 1 2 3 ... 127
uint8_t OLED_GRAM[128][8];

/*******************************************************************************
 * Static Function Declarations 
 ******************************************************************************/

/*******************************************************************************
 * Function Definitions 
 ******************************************************************************/
/*********************OLED写数据函数************************************/
void OLED_WrDat(unsigned char IIC_Data)
{
	fsp_err_t err;
	uint32_t timeout_ms = 500;
    uint8_t i2c_transmitter[2]={0x40, IIC_Data};

    // setting mutex for lock sci3_i2c bus
    if (pdTRUE == xSemaphoreTake(mutex_sci6_i2c, portMAX_DELAY))
    {
        R_SCI_I2C_SlaveAddressSet(&g_sci6_i2c_ctrl, 
                                OLED_I2C_SLAVE_ADDR_7BIT, 
                                I2C_MASTER_ADDR_MODE_7BIT);

        err = R_SCI_I2C_Write(&g_sci6_i2c_ctrl, i2c_transmitter, 0x02, true);
        assert(FSP_SUCCESS == err);
        
        /* Since there is nothing else to do, block until Callback triggers*/
        while ((I2C_MASTER_EVENT_TX_COMPLETE != sci6_i2c_event) && timeout_ms>0)
        {
            R_BSP_SoftwareDelay(1U, BSP_DELAY_UNITS_MICROSECONDS);
            timeout_ms--;
        }
        
        if (I2C_MASTER_EVENT_ABORTED == sci6_i2c_event)
        {
            // __BKPT(0);
			LOG("OLED: Write data failed\r\n");
        }
        /* Read data back from the I2C slave */
        sci6_i2c_event = I2C_MASTER_EVENT_ABORTED;

        // release the mutex, unlock
        (void)xSemaphoreGive(mutex_sci6_i2c);
    }
}

/*********************OLED写命令函数************************************/
void OLED_WrCmd(unsigned char IIC_Command)
{
	fsp_err_t err;
	uint32_t timeout_ms = 500;
    uint8_t i2c_transmitter[2]={0x00, IIC_Command};

    // setting mutex for lock sci3_i2c bus
    if (pdTRUE == xSemaphoreTake(mutex_sci6_i2c, portMAX_DELAY))
    {
        R_SCI_I2C_SlaveAddressSet(&g_sci6_i2c_ctrl, 
                                OLED_I2C_SLAVE_ADDR_7BIT, 
                                I2C_MASTER_ADDR_MODE_7BIT);

        err = R_SCI_I2C_Write(&g_sci6_i2c_ctrl, i2c_transmitter, 0x02, true);
        assert(FSP_SUCCESS == err);
        
        /* Since there is nothing else to do, block until Callback triggers*/
        while ((I2C_MASTER_EVENT_TX_COMPLETE != sci6_i2c_event) && timeout_ms>0)
        {
            R_BSP_SoftwareDelay(1U, BSP_DELAY_UNITS_MICROSECONDS);
            timeout_ms--;
        }
        
        if (I2C_MASTER_EVENT_ABORTED == sci6_i2c_event)
        {
            // __BKPT(0);
			LOG("OLED: Write command failed\r\n");
        }
        /* Read data back from the I2C slave */
        sci6_i2c_event = I2C_MASTER_EVENT_ABORTED;
        
        // release the mutex, unlock
        (void)xSemaphoreGive(mutex_sci6_i2c);
    }
}

//--------------------------------------------------------------
// Prototype      : void OLED_OFF(void)
// Calls          :
// Parameters     : none
// Description    : 让OLED休眠 -- 休眠模式下,OLED功耗不到10uA
//--------------------------------------------------------------
void OLED_OFF(void)
{
    OLED_WrCmd(0X8D);
    OLED_WrCmd(0X10);
    OLED_WrCmd(0XAE);
}


//--------------------------------------------------------------
// Prototype      : void OLED_ON(void)
// Calls          :
// Parameters     : none
// Description    : 将OLED从休眠中唤醒
//--------------------------------------------------------------
void OLED_ON(void)
{
    OLED_WrCmd(0X8D);
    OLED_WrCmd(0X14);
    OLED_WrCmd(0XAF);
}

//x1,y1,x2,y2 填充区域的对角坐标
//确保x1<=x2;y1<=y2 0<=x1<=127 0<=y1<=63
//dot:0,清空;1,填充
void OLED_Fill(uint8_t x1,uint8_t y1,uint8_t x2,uint8_t y2,uint8_t dot)
{
    uint8_t x,y;
    for(x=x1;x<=x2;x++)
        for(y=y1;y<=y2;y++)
            OLED_DrawPoint(x,y,dot);
    OLED_Refresh_Gram();//更新显示
}

//清屏函数,清完屏,整个屏幕是黑色的!和没点亮一样!!!
void OLED_Clear(void)
{
    uint8_t i,n;
    for(i=0;i<8;i++)
        for(n=0;n<128;n++)
            OLED_GRAM[n][i]=0X00;
    // OLED_Refresh_Gram();//更新显示
}

/*********************OLED初始化************************************/
void OLED_Init(void)
{
	R_BSP_SoftwareDelay(500, BSP_DELAY_UNITS_MILLISECONDS);

    OLED_WrCmd(0xAE); //关闭显示
    OLED_WrCmd(0xD5); //设置时钟分频因子,震荡频率
    OLED_WrCmd(80);   //[3:0],分频因子;[7:4],震荡频率
    OLED_WrCmd(0xA8); //设置驱动路数
    OLED_WrCmd(0X3F); //默认0X3F(1/64)
    OLED_WrCmd(0xD3); //设置显示偏移
    OLED_WrCmd(0X00); //默认为0

    OLED_WrCmd(0x40); //设置显示开始行 [5:0],行数.

    OLED_WrCmd(0x8D); //电荷泵设置
    OLED_WrCmd(0x14); //bit2，开启/关闭
    OLED_WrCmd(0x20); //设置内存地址模式
    OLED_WrCmd(0x02); //[1:0],00，列地址模式;01，行地址模式;10,页地址模式;默认10;
    OLED_WrCmd(0xA1); //段重定义设置,bit0:0,0->0;1,0->127;
    OLED_WrCmd(0xC0); //设置COM扫描方向;bit3:0,普通模式;1,重定义模式 COM[N-1]->COM0;N:驱动路数
    OLED_WrCmd(0xDA); //设置COM硬件引脚配置
    OLED_WrCmd(0x12); //[5:4]配置

    OLED_WrCmd(0x81); //对比度设置
    OLED_WrCmd(0xEF); //1~255;默认0X7F (亮度设置,越大越亮)
    OLED_WrCmd(0xD9); //设置预充电周期
    OLED_WrCmd(0xf1); //[3:0],PHASE 1;[7:4],PHASE 2;
    OLED_WrCmd(0xDB); //设置VCOMH 电压倍率
    OLED_WrCmd(0x30); //[6:4] 000,0.65*vcc;001,0.77*vcc;011,0.83*vcc;

    OLED_WrCmd(0xA4); //全局显示开启;bit0:1,开启;0,关闭;(白屏/黑屏)
    OLED_WrCmd(0xA6); //设置显示方式;bit0:1,反相显示;0,正常显示
    OLED_WrCmd(0xAF); //开启显示

    OLED_Clear();
}

//更新显存到LCD
void OLED_Refresh_Gram(void)
{
    uint8_t i,n;
    for(i=0;i<8;i++)
    {
        OLED_WrCmd (0xb0+i);    //设置页地址（0~7）
        OLED_WrCmd (0x00);      //设置显示位置—列低地址
        OLED_WrCmd (0x10);      //设置显示位置—列高地址
        for(n=0;n<128;n++)
            OLED_WrDat(OLED_GRAM[n][i]);
    }
}

//画点
//x:0~127
//y:0~63
//t:1 填充 0,清空
void OLED_DrawPoint(uint8_t x,uint8_t y,uint8_t t)
{
    uint8_t pos,bx,temp=0;
    if(x>127||y>63)return;//超出范围了.
    pos=7-y/8;
    bx=y%8;
    temp=(uint8_t)(1U<<(7U-bx));
    if(t)
        OLED_GRAM[x][pos]|=temp;
    else
        OLED_GRAM[x][pos]&=~temp;
}

//在指定位置显示一个字符,包括部分字符
//x:0~127
//y:0~63
//mode:0,反白显示;1,正常显示
//size:选择字体 16/12
void OLED_ShowChar(uint8_t x,uint8_t y,uint8_t chr,uint8_t size,uint8_t mode)
{
    uint8_t temp,t,t1;
    uint8_t y0=y;
    uint8_t csize=(size/8+((size%8)?1:0))*(size/2);      //得到字体一个字符对应点阵集所占的字节数
    chr=chr-' ';//得到偏移后的值
    for(t=0;t<csize;t++)
    {
        if(size==12)temp=asc2_1206[chr][t];         //调用1206字体
        else if(size==16)temp=asc2_1608[chr][t];    //调用1608字体
        else if(size==24)temp=asc2_2412[chr][t];    //调用2412字体
        else if(size==36)temp=asc2_3618[chr][t];    //调用3618字体
        else return;                                //没有的字库
        for(t1=0;t1<8;t1++)
        {
            if(temp&0x80)
                OLED_DrawPoint(x,y,mode);
            else OLED_DrawPoint(x,y,!mode);
            temp<<=1;
            y++;
            if((y-y0)==size)
            {
                y=y0;
                x++;
                break;
            }
        }
    }
}

//显示字符串
//x,y:起点坐标
//size:字体大小
//*p:字符串起始地址
void OLED_ShowString(uint8_t x,uint8_t y,const uint8_t *p,uint8_t size,uint8_t mode)
{
    while((*p<='~')&&(*p>=' '))
    {
        if(x>(128-(size/2))){x=0;y+=size;}
        if(y>(64-size)){y=x=0;OLED_Clear();}
        OLED_ShowChar(x,y,*p,size,mode);
        x+=size/2;
        p++;
    }
}

//m^n函数
uint32_t mypow(uint8_t m, uint8_t n)
{
    uint32_t result = 1;

    while(n--)
        result *= m;

    return result;
}
//显示2个数字
//x,y :起点坐标
//len :数字的位数
//size:字体大小
//mode:模式  0,填充模式;1,叠加模式
//num:数值(0~4294967295);
void OLED_ShowNum(uint8_t x, uint8_t y, uint32_t num, uint8_t len, uint8_t size, uint8_t mode)
{
    uint8_t t, temp;
    uint8_t enshow = 0;

    for(t=0; t<len; t++)
    {
        temp = (num / mypow(10,len-t-1)) % 10;
        if((enshow == 0) && (t < (len-1)))
        {
            if(temp == 0)
            {
                OLED_ShowChar(x+(size/2)*t,y,'0',size, mode);

                continue;
            }
            else
                enshow = 1;
        }
        OLED_ShowChar(x+(size/2)*t,y,temp+'0',size, mode);
    }
}

//在指定位置显示一个汉字
//x:0~127
//y:0~63
//hz_c:输入汉字，汉字需要先建模
//mode:0,反白显示;1,正常显示
void OLED_ShowHz(uint8_t x, uint8_t y, const char hz_c[], uint8_t mode)
{
    uint8_t temp, t, t1;
    uint8_t y0 = y;
    uint8_t csize = 32u;
    uint8_t chr = 0;
    uint8_t flag = 0;

    for (t=0; t<(sizeof(hz_char)/sizeof(hz_char[0])); t++)
    {
        if(strcmp(hz_char[t], hz_c) == 0)
        {
            chr = t;
            flag = 1;    //找到了建模的汉字
            break;
        }
    }

    if(1 == flag)
    {
        chr <<= 1u;

        for(t=0; t<csize; t++)
        {
            if(16U == t)
                chr += 1;

            temp=(0 == mode) ? (hz_code[chr][t%16]):(~hz_code[chr][t%16]);

            for(t1=0; t1<8; t1++)
            {
                if(temp & 0x80)
                    OLED_DrawPoint(x, y, 0);
                else
                    OLED_DrawPoint(x, y, 1);

                temp <<= 1;
                y++;
                if(16U == (y-y0))
                {
                    y = y0;
                    x++;
                    break;
                }
            }
        }
    }
}

//显示连续的汉字,一行显示，一行128像素，最多显示8个
//hz_len: 要显示的函数的长度
//汉字大小为16像素，其他像素的汉字暂时不支持
//一个汉字的长度为三个字节，并且包含一个结束符
void OLED_ShowHzStringRow(uint8_t x, uint8_t y, const char *hz_s, uint8_t mode)
{
    uint8_t i;
    char chr[4];
    uint8_t len;

    len = (uint8_t)strlen(hz_s);    //计算汉字字符串的长度

    for(i=0; i<(len-1); i+=3)
    {
        sprintf(chr, "%c%c%c", hz_s[i], hz_s[i+1], hz_s[i+2]);
        OLED_ShowHz(x+(uint8_t)((i/3U)<<4U), y, chr, mode);
    }
}

//显示连续的汉字，一列显示，一列64像素最多显示4个
//hz_len: 要显示的函数的长度
//汉字大小为16像素，其他像素的汉字暂时不支持
//一个汉字的长度为三个字节，并且包含一个结束符
void OLED_ShowHzStringColumn(uint8_t x, uint8_t y, const char *hz_s, uint8_t mode)
{
    uint8_t i;
    char chr[4];
    uint8_t len;

    len = (uint8_t)strlen(hz_s);    //计算汉字字符串的长度

    for(i=0; i<(len-1); i+=3)
    {
        sprintf(chr, "%c%c%c", hz_s[i], hz_s[i+1], hz_s[i+2]);
        OLED_ShowHz(x, y+(uint8_t)((i/3U)<<4U), chr, mode);
    }
}

//在指定位置显示一个汉字
//x:0~127
//y:0~63
//chr:汉字的索引
//mode:0,反白显示;1,正常显示
void OLED_ShowHzFromIndex(uint8_t x, uint8_t y, uint8_t chr, uint8_t mode)
{
    uint8_t temp, t, t1;
    uint8_t y0 = y;
    uint8_t csize = 32u;

    chr <<= 1u;

    for(t=0; t<csize; t++)
    {
        if(16U == t)
            chr += 1;

        temp=(0 == mode) ? (hz_code[chr][t%16]):(~hz_code[chr][t%16]);

        for(t1=0; t1<8; t1++)
        {
            if(temp & 0x80)
                OLED_DrawPoint(x, y, 0);
            else
                OLED_DrawPoint(x, y, 1);

            temp <<= 1;
            y++;
            if(16U == (y-y0))
            {
                y = y0;
                x++;
                break;
            }
        }
    }
}

//OLED字符串连续显示函数
void OLED_HzStringFromIndex(uint8_t x, uint8_t y, uint8_t chr_S, uint8_t chr_E, uint8_t mode)
{
    uint8_t i;

    for(i=chr_S; i<=chr_E; i++)
    {
        OLED_ShowHzFromIndex(x+16*(i-chr_S), y, i, mode);
    }
}

void OLED_DrawBmpImg(uint8_t x,
                     uint8_t y,
                     const uint8_t bmp[][16],
                     uint32_t len,
                     uint8_t mode)
{
    uint16_t t, t1;
    uint8_t  y0 = y;
    uint8_t  temp = 0u;
    uint16_t len2 = (uint16_t)(len>>4u);

    for(t=0; t<len; t++)
    {
        temp=(0 == mode) ?
             (bmp[(uint8_t)(t/16)][(uint8_t)(t%16)]):(~bmp[(uint8_t)(t/16)][(uint8_t)(t%16)]);

        for(t1=0; t1<8; t1++)
        {
            if(temp & 0x80)
                OLED_DrawPoint(x, y, 0);
            else
                OLED_DrawPoint(x, y, 1);

            temp <<= 1u;
            y++;
            if((y-y0) == len2)
            {
                y = y0;
                x ++;
                break;
            }
        }
    }
}

void OLED_DrawBmpImg2(uint8_t x,
                     uint8_t y,
                     const uint8_t bmp[][8],
                     uint32_t len,
                     uint8_t size,
                     uint8_t mode)
{
    uint16_t t, t1;
    uint8_t  y_end;
    uint8_t  temp;
    uint16_t len2 = 0u;

    y_end = y;

    len2 = (uint16_t)((len) / ((uint8_t)(size/8)));

    for(t=0; t<len; t++)
    {
        temp=(0 == mode) ?
             (bmp[(uint8_t)(t/8)][(uint8_t)(t%8)]):(~bmp[(uint8_t)(t/8)][(uint8_t)(t%8)]);

        for(t1=0; t1<8; t1++)
        {
            if(temp&0x80)
                OLED_DrawPoint(x, y, 0);
            else
                OLED_DrawPoint(x, y, 1);

            temp <<= 1u;
            y++;
            if((y-y_end) == len2)
            {
                y = y_end;
                x ++;
                break;
            }
        }
    }
}
